import api from '../utils/api';
import { Banner } from '../types';

export interface BannerListParams {
  keyword?: string;
  platform?: string;
  isActive?: string;
  page?: number;
  limit?: number;
  sort?: string;
}

export interface BannerListResponse {
  success: boolean;
  data: Banner[];
  pagination: {
    current: number;
    pageSize: number;
    total: number;
    pages: number;
  };
}

export interface BannerResponse {
  success: boolean;
  data: Banner;
  message?: string;
}

export interface CreateBannerData {
  title: string;
  image: string;
  link?: string;
  linkType?: 'product' | 'category' | 'shop' | 'external' | 'none';
  linkTarget?: string;
  order?: number;
  isActive?: boolean;
  startDate?: string;
  endDate?: string;
  description?: string;
  platform?: 'mobile' | 'web' | 'all';
}

export interface UpdateBannerData extends Partial<CreateBannerData> { }

export interface BannerStats {
  success: boolean;
  data: {
    totalBanners: number;
    activeBanners: number;
    inactiveBanners: number;
    totalClicks: number;
    platformStats: {
      [key: string]: {
        count: number;
        clicks: number;
      };
    };
  };
}

class BannerService {
  /**
   * 获取轮播图列表
   */
  async getBanners(params: BannerListParams = {}): Promise<BannerListResponse> {
    try {
      const response = await api.get<BannerListResponse>('/admin/banners', { params });
      return response;
    } catch (error) {
      console.error('获取轮播图列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取单个轮播图详情
   */
  async getBanner(id: string): Promise<BannerResponse> {
    try {
      const response = await api.get<BannerResponse>(`/admin/banners/${id}`);
      return response;
    } catch (error) {
      console.error('获取轮播图详情失败:', error);
      throw error;
    }
  }

  /**
   * 创建轮播图
   */
  async createBanner(data: CreateBannerData): Promise<BannerResponse> {
    try {
      const response = await api.post<BannerResponse>('/admin/banners', data);
      return response;
    } catch (error) {
      console.error('创建轮播图失败:', error);
      throw error;
    }
  }

  /**
   * 更新轮播图
   */
  async updateBanner(id: string, data: UpdateBannerData): Promise<BannerResponse> {
    try {
      const response = await api.put<BannerResponse>(`/admin/banners/${id}`, data);
      return response;
    } catch (error) {
      console.error('更新轮播图失败:', error);
      throw error;
    }
  }

  /**
   * 删除轮播图
   */
  async deleteBanner(id: string): Promise<{ success: boolean; message: string }> {
    try {
      const response = await api.delete<{ success: boolean; message: string }>(`/admin/banners/${id}`);
      return response;
    } catch (error) {
      console.error('删除轮播图失败:', error);
      throw error;
    }
  }

  /**
   * 批量删除轮播图
   */
  async batchDeleteBanners(ids: string[]): Promise<{ success: boolean; message: string; deletedCount: number }> {
    try {
      const response = await api.post<{ success: boolean; message: string; deletedCount: number }>('/admin/banners/batch-delete', { ids });
      return response;
    } catch (error) {
      console.error('批量删除轮播图失败:', error);
      throw error;
    }
  }

  /**
   * 更新轮播图状态
   */
  async updateBannerStatus(id: string, isActive: boolean): Promise<BannerResponse> {
    try {
      const response = await api.patch<BannerResponse>(`/admin/banners/${id}/status`, { isActive });
      return response;
    } catch (error) {
      console.error('更新轮播图状态失败:', error);
      throw error;
    }
  }

  /**
   * 获取轮播图统计信息
   */
  async getBannerStats(startDate?: string, endDate?: string): Promise<BannerStats> {
    try {
      const params: any = {};
      if (startDate) params.startDate = startDate;
      if (endDate) params.endDate = endDate;

      const response = await api.get<BannerStats>('/banners/stats', { params });
      return response;
    } catch (error) {
      console.error('获取轮播图统计失败:', error);
      throw error;
    }
  }

  /**
   * 记录轮播图点击
   */
  async recordClick(id: string): Promise<{ success: boolean; message: string; clickCount: number }> {
    try {
      const response = await api.post<{ success: boolean; message: string; clickCount: number }>(`/banners/${id}/click`);
      return response;
    } catch (error) {
      console.error('记录轮播图点击失败:', error);
      throw error;
    }
  }

  /**
   * 上传图片
   */
  async uploadImage(file: File): Promise<{ success: boolean; url: string }> {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await api.post<{
        success: boolean;
        message: string;
        data: {
          filename: string;
          originalname: string;
          size: number;
          url: string;
          path: string;
        };
      }>('/upload/banner', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      return {
        success: response.success,
        url: response.data.url
      };
    } catch (error) {
      console.error('上传图片失败:', error);
      throw error;
    }
  }

  /**
   * 删除图片
   */
  async deleteImage(filename: string): Promise<{ success: boolean; message: string }> {
    try {
      const response = await api.delete<{ success: boolean; message: string }>(`/upload/banner/${filename}`);
      return response;
    } catch (error) {
      console.error('删除图片失败:', error);
      throw error;
    }
  }
}

export default new BannerService();
